package apis

import (
	"container/list"
	"math"
	"reflect"
)

var baseStr string = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ"
var base []byte = []byte(baseStr)

// @Summary 切片分页
// @Param pageIndex 当前页
// @Param pageSize 每页显示数量
// @Param count 数据总数
// @return sliceStart 切片开始
// @return sliceEnd 切片结尾
func SlicePage(pageIndex, pageSize, count int) (sliceStart, sliceEnd int) {
	if pageIndex < 0 {
		pageIndex = 1
	}

	if pageSize < 0 {
		pageSize = 20
	}

	if pageSize > count {
		return 0, count
	}

	// 总页数
	pageCount := int(math.Ceil(float64(count) / float64(pageSize)))
	if pageIndex > pageCount {
		return 0, 0
	}
	sliceStart = (pageIndex - 1) * pageSize
	sliceEnd = sliceStart + pageSize

	if sliceEnd > count {
		sliceEnd = count
	}
	return sliceStart, sliceEnd
}

func ProcessRandomObject(n uint64) string {
	quotient := n
	mod := uint64(0)
	l := list.New()
	for quotient != 0 {
		mod = quotient % 34
		quotient = quotient / 34
		l.PushFront(base[int(mod)])
	}
	listLen := l.Len()
	if listLen >= 6 {
		res := make([]byte, 0, listLen)
		for i := l.Front(); i != nil; i = i.Next() {
			res = append(res, i.Value.(byte))
		}
		return string(res[0:6])
	} else {
		res := make([]byte, 0, 6)
		for i := 0; i < 6; i++ {
			if i < 6-listLen {
				res = append(res, base[0])
			} else {
				res = append(res, l.Front().Value.(byte))
				l.Remove(l.Front())
			}

		}
		return string(res)
	}

}

func Slice2Map(slice interface{}, keyName string) interface{} {
	sliceType := reflect.TypeOf(slice)
	if sliceType.Kind() != reflect.Slice {
		return nil
	}
	valOf := reflect.ValueOf(slice)
	length := valOf.Len()
	if length == 0 {
		return nil
	}
	// 获得map对应类型
	mapT := reflect.MapOf(valOf.Index(0).FieldByName(keyName).Type(), valOf.Index(0).Type())
	mapV := reflect.MakeMap(mapT)
	for i := 0; i < length; i++ {
		structType := reflect.TypeOf(valOf.Index(i))
		if structType.Kind() != reflect.Struct {
			return nil
		}
		//mapV[struOf.FieldByName(keyName)] = struOf
		mapV.SetMapIndex(valOf.Index(i).FieldByName(keyName), valOf.Index(i))
	}
	return mapV
}
